package com.android.lovingpet.util;

/**
 * Created by ikata on 2018/4/29.
 */

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;


/**
 * Created by ikata on 2018/2/19.
 */

public class MyHttp {

    private OkHttpClient client;
    private static MyHttp instance;

    public synchronized static MyHttp getInstance() {
        if (instance == null) {
            instance = new MyHttp();
        }
        return instance;
    }
    private MyHttp() {
        client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();
    }

    private  Request buildMultipartFormRequest(String url, @Nullable String sessionId, Map<String,String> params,Map<String,File> files)
    {
        Request.Builder builder=new Request.Builder();
        if (!TextUtils.isEmpty(sessionId)) {
            builder.addHeader("cookie", sessionId);
        }
        builder.url(url).post(buildMultipartRequestBody(params,files));
        return builder.build();
    }
    private RequestBody buildMultipartRequestBody(Map<String,String> params,Map<String,File> files)
    {
        MultipartBody.Builder builder=new MultipartBody.Builder();
        for (Map.Entry<String, String> map : params.entrySet()) {
            String key = map.getKey();
            String value;
            /**
             * 判断值是否是空的
             */
            if (map.getValue() == null) {
                value = "";
            } else {
                value = map.getValue();
            }
            /**
             * 把key和value添加到formBody中
             */
            builder.addFormDataPart(key, value);
        }
        for (Map.Entry<String,File> entry:files.entrySet())
        {
            builder.addFormDataPart(entry.getKey(),entry.getValue().getName(),RequestBody.create(MediaType.parse("application/octet-stream "),entry.getValue()));
        }
        return builder.build();
    }

    private  Request buildMultipartFormRequest(String url, @Nullable String sessionId, String[] fileKeys, File[] files, HashMap<String,String> params)
    {

        MultipartBody.Builder builder=new MultipartBody.Builder();
        for (Map.Entry<String, String> map : params.entrySet()) {
            String key = map.getKey();
            String value;
            /**
             * 判断值是否是空的
             */
            if (map.getValue() == null) {
                value = "";
            } else {
                value = map.getValue();
            }
            /**
             * 把key和value添加到formBody中
             */
            builder.addFormDataPart(key, value);
        }
        if (files != null)
        {
            RequestBody fileBody = null;
            for (int i = 0; i < files.length; i++)
            {
                File file = files[i];
                fileBody = RequestBody.create(MediaType.parse("video/mp4"), file);
                String fileName = file.getName();
                builder.addFormDataPart(fileKeys[i],fileName,fileBody);
            }
        }
        RequestBody requestBody = builder.build();

        Request.Builder builder1=new Request.Builder();
        builder1.addHeader("cookie",sessionId).url(url).post(requestBody);
        return builder1.build();
    }

    private Request buildRequest(String url, @Nullable String sessionId, Map<String,String> params)
    {
        Request.Builder builder=new Request.Builder();
        if (!TextUtils.isEmpty(sessionId)) {
            builder.addHeader("cookie", sessionId);
        }
        builder.url(url).post(buildRequestBody(params));
        return builder.build();
    }
    private RequestBody buildRequestBody(Map<String,String> params)
    {
        FormBody.Builder builder=new FormBody.Builder();
        for (Map.Entry<String, String> map : params.entrySet()) {
            String key = map.getKey();
            String value;
            /**
             * 判断值是否是空的
             */
            if (map.getValue() == null) {
                value = "";
            } else {
                value = map.getValue();
            }
            /**
             * 把key和value添加到formBody中
             */
            Log.d(key, value);
            builder.add(key, value);
        }
        FormBody body = builder.build();
        Log.d("body", body.toString());
        return body;
    }


    public void postAsync(@NonNull String sessionId, String url, Map<String, String> params, Map<String, File> files, Callback callback) {
        getInstance().client.newCall(buildMultipartFormRequest(url,sessionId,params,files)).enqueue(callback);
    }
    public void postAsync(@Nullable String sessionId, String url, String key, String value, Callback callback)
    {
        Request.Builder builder=new Request.Builder();
        if (!TextUtils.isEmpty(sessionId))
        {
            builder.addHeader("cookie",sessionId);
        }
        FormBody.Builder body=new FormBody.Builder();
        RequestBody requestBody= body.add(key,value).build();
        builder
                .url(url)
                .post(requestBody);

        getInstance().client.newCall(builder.build()).enqueue(callback);
    }
    public  void postAsync(@Nullable String sessionId, String url, Map<String,String> params, Callback callback)
    {
        client.newCall( buildRequest(url,sessionId,params)).enqueue(callback);
    }

    public  void postAsync(@Nullable String sessionId,String url, HashMap<String,String> params,String[] fileKey, File[] file,Callback callback)
    {
        client.newCall(buildMultipartFormRequest(url,sessionId,fileKey,file,params)).enqueue(callback);
    }

    public static String getCodeString(int code)
    {
        switch (code) {
            case -1:return "系统错误";
            case 0:return  "操作成功";
            case 1:return  "参数错误";
            case 2:return  "用户不存在或密码错误";
            case 4:return  "用户已存在";
            case 5:return "用户未登陆";
            case 7:return "过期失效";
            case 8:return "邮箱已验证过";
            case 9:return "邮箱已被某用户绑定";
            case 11:return "账户未激活";
            case 12:return "参数错误";
            default:return "未知错误";
        }
    }
    public static String getFailureMeg() {
        return "连接失败，请检查网络设置";
    }

    public static int getCode(String responseData)
    {
        try {
            JSONObject jsonObject=new JSONObject(responseData);
            Log.d("responseData",responseData);
            int code=jsonObject.getInt("code");
            return code;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return -2;
    }
    public  void getAsyn(String url,String sessionId,Callback callback){
        OkHttpClient okHttpClient=new OkHttpClient();
        RequestBody requestBody=new FormBody.Builder().build();
        final Request request=new Request.Builder()
                .addHeader("cookie",sessionId)
                .url(url)
                .post(requestBody)
                .build();
        Call call=okHttpClient.newCall(request);
        call.enqueue(callback);
    }
}
